package me.ezjs.web.config.interceptor;

import me.ezjs.base.thread.ThreadContext;
import me.ezjs.core.util.StringUtil;
import me.ezjs.web.config.InterceptorConfig;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by junli on 2017/8/21.
 */
public class StaffInfoInterceptor implements HandlerInterceptor{

    private String devModel(HttpServletRequest request) {
        String staff_id = request.getHeader("staff_id");
        if (StringUtil.isNull(staff_id) && InterceptorConfig.DEV_MODEL) return "1";
        return staff_id;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String staffIdFromHeader = devModel(request);
        if (StringUtil.isNull(staffIdFromHeader)) {
            return true; //header中不包含企业信息, 继续
        }
        try {
            Integer staffId = Integer.parseInt(staffIdFromHeader);
            /* 存入ThreadLocal */
            ThreadContext.setStaffId(staffId);
            return true;
        } catch (NumberFormatException e) {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
